package com.shuosen.gmall.passport.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.shuosen.gmall.bean.UserInfo;
import com.shuosen.gmall.passport.config.JwtUtil;
import com.shuosen.gmall.service.Userservice;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class PassportController {


    @Value("${token.key}")
    private String signKey;

    @Reference
    private Userservice userservice;

    @RequestMapping("index")
    public String index(HttpServletRequest request) {
        String orginUrl = request.getParameter("originUrl");
        request.setAttribute("originUrl", orginUrl);
        return "index";
    }

    @RequestMapping("login")
    @ResponseBody
    public String login(UserInfo userInfo, HttpServletRequest request) {

        //获取服务器的ip地址
        String remoteAddr = request.getHeader("X-forwarded-for");

        if (userInfo != null) {
            //调用服务层去登录
            UserInfo loginUser = userservice.login(userInfo);
            if (loginUser == null) {
                return "fail";
            } else {
                Map map = new HashMap();
                map.put("userId", loginUser.getId());
                map.put("nickName", loginUser.getNickName());
                String token = JwtUtil.encode(signKey, map, remoteAddr);
                return token;
            }
        }
        return "fail";
    }

    @RequestMapping("verify")
    @ResponseBody
    public String verfify(HttpServletRequest request) {
        //如何知道是否登录
        String salt = request.getHeader("x-forwarded-for");
//        String  salt = request.getParameter("salt");
        String token = request.getParameter("token");

        //解密token，能获得user信息
        Map<String, Object> map = JwtUtil.decode(token, signKey, salt);
        if (map != null) {
            //检查redis信息
            String userId = (String) map.get("userId");
            UserInfo userInfo = userservice.verfiy(userId);
            if (userInfo != null) {
                return "success";
            }
        }
        return "fail";
    }

}
